import * as React from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { useAuth } from '@/providers/auth-provider'
import { X } from 'lucide-react'

interface ProfileModalProps {
    open: boolean
    onClose: () => void
}

export function ProfileModal({ open, onClose }: ProfileModalProps) {
    const { user, updateProfile, isLoading } = useAuth()
    const [name, setName] = React.useState('')
    const [avatar, setAvatar] = React.useState<File | null>(null)
    const [avatarPreview, setAvatarPreview] = React.useState('')
    const [error, setError] = React.useState<string | null>(null)
    const [success, setSuccess] = React.useState<string | null>(null)

    React.useEffect(() => {
        if (open && user) {
            // 初始化表单状态
            setName(user.name || '')
            setAvatar(null)
            setAvatarPreview(user.avatar || '')
            setError(null)
            setSuccess(null)
        }
    }, [open, user])

    const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0]
        if (file) {
            setAvatar(file)
            const reader = new FileReader()
            reader.onload = (e) => {
                setAvatarPreview(e.target?.result as string)
            }
            reader.readAsDataURL(file)
        }
    }

    const onSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        setError(null)
        setSuccess(null)
        
        try {
            const updateData: { name?: string; avatar?: File } = {}
            if (name && name !== user?.name) updateData.name = name
            if (avatar) updateData.avatar = avatar
            
            if (Object.keys(updateData).length === 0) {
                setError('没有检测到任何修改')
                return
            }
            
            await updateProfile(updateData)
            setSuccess('资料更新成功！')
            setTimeout(() => {
                onClose()
            }, 1500)
        } catch (err: any) {
            setError(err?.message ?? '更新失败')
        }
    }

    const handleBackdropClick = (e: React.MouseEvent) => {
        if (e.target === e.currentTarget) {
            onClose()
        }
    }

    if (!open || !user) return null

    return (
        <div 
            className="fixed inset-0 z-[100] bg-black/50 backdrop-blur-sm flex items-center justify-center p-4"
            onClick={handleBackdropClick}
        >
            <Card className="w-full max-w-md md:max-w-lg bg-white shadow-2xl border-0 relative">
                <Button
                    variant="ghost"
                    size="icon"
                    className="absolute right-2 top-2 h-8 w-8"
                    onClick={onClose}
                >
                    <X className="h-4 w-4" />
                </Button>
                <CardHeader>
                    <CardTitle>编辑资料</CardTitle>
                    <CardDescription>修改您的个人信息</CardDescription>
                </CardHeader>
                <CardContent>
                    <form className="space-y-4" onSubmit={onSubmit}>
                        <div className="space-y-1">
                            <label className="text-sm">姓名</label>
                            <Input 
                                value={name} 
                                onChange={(e) => setName(e.target.value)} 
                                placeholder="请输入姓名"
                                autoFocus
                            />
                        </div>
                        <div className="space-y-1">
                            <label className="text-sm">头像</label>
                            <Input 
                                type="file"
                                accept="image/*"
                                onChange={handleAvatarChange} 
                                placeholder="选择头像图片"
                            />
                            {(avatarPreview && avatarPreview.trim() !== '') ? (
                                <div className="mt-2 flex items-center gap-3">
                                    <Avatar className="h-16 w-16">
                                        <AvatarImage 
                                            src={avatarPreview} 
                                            alt="头像预览" 
                                        />
                                        <AvatarFallback className="text-lg">
                                            {user.name?.slice(0, 1)?.toUpperCase() ?? 'U'}
                                        </AvatarFallback>
                                    </Avatar>
                                    <span className="text-sm text-gray-600">头像预览</span>
                                </div>
                            ) : (
                                <div className="mt-2 flex items-center gap-3">
                                    <Avatar className="h-16 w-16">
                                        <AvatarFallback className="text-lg">
                                            {user.name?.slice(0, 1)?.toUpperCase() ?? 'U'}
                                        </AvatarFallback>
                                    </Avatar>
                                    <span className="text-sm text-gray-500">没有头像时显示用户名首字母</span>
                                </div>
                            )}
                        </div>
                        <div className="space-y-1">
                            <label className="text-sm">手机号</label>
                            <Input 
                                value={user.phone} 
                                disabled 
                                className="bg-gray-50"
                            />
                            <p className="text-xs text-gray-500">手机号不可修改</p>
                        </div>
                        {user.email !== null && (
                            <div className="space-y-1">
                                <label className="text-sm">邮箱</label>
                                <Input 
                                    value={user.email || ''} 
                                    disabled 
                                    className="bg-gray-50"
                                />
                                <p className="text-xs text-gray-500">邮箱不可修改</p>
                            </div>
                        )}
                        <div className="space-y-1">
                            <label className="text-sm text-gray-500">其他信息</label>
                            <div className="text-xs text-gray-500 space-y-1">
                                <p>ID: {user.id}</p>
                                <p>状态: {user.status === 0 ? '正常' : '禁用'}</p>
                                {user.created_at && <p>注册时间: {user.created_at}</p>}
                                {user.updated_at && <p>更新时间: {user.updated_at}</p>}
                            </div>
                        </div>
                        {error ? <p className="text-sm text-destructive">{error}</p> : null}
                        {success ? <p className="text-sm text-green-600">{success}</p> : null}
                        <Button className="w-full h-10" disabled={isLoading}>
                            {isLoading ? '更新中...' : '更新资料'}
                        </Button>
                    </form>
                </CardContent>
            </Card>
        </div>
    )
}